/*
 * ForSaleDAO.java
 *
 * Created on March 22, 2007, 1:45 PM
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */

package edu.byu.isys413.group1E.data;

import edu.byu.isys413.group1E.*;
import java.sql.*;
import java.util.ArrayList;

/**
 *
 * @author Kendall Frazier
 */
public class ForSaleDAO extends PhysicalDAO{
    private static ForSaleDAO instance = null;
    
    /** Creates a new instance of ForSaleDAO */
    public ForSaleDAO() {
    }
    
    /**Retrieves an instance of the TransactionDAO object**/
    public static synchronized ForSaleDAO getInstance() {
        if (instance == null) {
            instance = new ForSaleDAO();
        }
        return instance;
    }
    
    ///////////////////////////////////////////////////////////////////////////////
    /////////   CREATE
    /**
     *creates the forSaleBO  
     *
     * @throws java.lang.Exception 
     * @return ForSaleBO
     */
    public ForSaleBO create() throws Exception{
        String id = GUID.generate();
        ForSaleBO bo = new ForSaleBO(id);
        Cache c = Cache.getInstance();
        c.put(bo.getProductID(), bo);
        return bo;
    }
    
    /**
     *reads in the ForSaleBO based on the ID 
     *
     * @param id 
     * @throws java.sql.SQLException 
     * @throws edu.byu.isys413.group1E.DataException 
     * @throws edu.byu.isys413.group1E.ConnectionPoolException 
     * @return ProductBO
     */
    public ProductBO read(String id) throws SQLException, DataException, ConnectionPoolException {
        // check to see if id in the cache
        Cache c = Cache.getInstance();
        ForSaleBO forSale = (ForSaleBO)c.get(id);
        if (forSale != null){
            return forSale;                                                        // if so, return it immediately
        }
        
        //otherwise, get it from the database
        try {
            Connection conn = ConnectionPool.getInstance().get();             // retrieve a database connection from the pool
            forSale = (ForSaleBO)this.read(id, conn);                                              // call read with a connection
            conn.commit();
            ConnectionPool.getInstance().release(conn);                       // release the connection
        }catch (SQLException e) {
            //rollback
            throw new DataException("Could not retrieve record for id = " + id, e);
        }catch (ConnectionPoolException x) {
            //rollback
            throw new ConnectionPoolException("Could not establish connection to database.", x);
        }
        
        // release the connection back to the pool
        return forSale;
    }
    
    /**
     * 
     * @param id 
     * @param conn 
     * @throws java.sql.SQLException 
     * @throws edu.byu.isys413.group1E.DataException 
     * @throws edu.byu.isys413.group1E.ConnectionPoolException 
     * @return 
     */
    public synchronized ProductBO read(String id, Connection conn) throws SQLException, DataException, ConnectionPoolException {
        // check to see if id in the cache
        Cache c = Cache.getInstance();
        ForSaleBO forSale = (ForSaleBO)c.get(id);
        if (forSale != null){
            return forSale;                                                        // if so, return it immediately
        }
        //put it to the cache so the super.read can get it
        forSale = new ForSaleBO(id);
        c.put(id, forSale);
        // if not in the cache, get a result set from
        // a SELECT * FROM table WHERE id=guid
        forSale = (ForSaleBO)super.read(id, conn);
        
        Statement stmt = conn.createStatement();
        ResultSet rs = stmt.executeQuery("SELECT * FROM For_Sale WHERE ProductID = '" + id + "'");
        conn.commit();
        
        //build the object from the result set
        if (rs.next()) {
            int temp;
            
            //temp = 0 means the product is used, 1 means it's new
            temp = rs.getInt("NEW_USED");
            if(temp == 0){
                forSale.setNewUsed(false);
            }
            else{
                forSale.setNewUsed(true);
            }
            
            temp = rs.getInt("SOLD");
            if(temp == 0){
                forSale.setSold(false);
            }
            else{
                forSale.setSold(true);
            }
            
            forSale.setAlreadyInDB(true);
            forSale.setDirty(false);
            
            // save to the cache
            c.put(forSale.getProductID(), forSale);
        }else{
            throw new DataException("Object was not found in the database.");
        }
        stmt.close();
        // return the BO
        return forSale;
    }
    
    /**
     * 
     * @throws edu.byu.isys413.group1E.DataException 
     * @throws java.sql.SQLException 
     * @throws edu.byu.isys413.group1E.ConnectionPoolException 
     * @return 
     */
    public synchronized ArrayList<ProductBO> readAll() throws DataException, SQLException, ConnectionPoolException{
//        ProductDAO prodDAO = ProductDAO.getInstance();
        ArrayList<ProductBO> list = new ArrayList<ProductBO>();
//now build the query
        String query = "SELECT * FROM ForSale";
        
        Connection conn = ConnectionPool.getInstance().get();
        Statement stmt = conn.createStatement();
        ResultSet rs = stmt.executeQuery(query);
        conn.commit();
        
//extract the elements from the result set and build a list of results
//build the object from the result set
        while (rs.next()) {
            ForSaleBO ForSale = new ForSaleBO(rs.getString("ProductID"));
            Cache.getInstance().put(rs.getString("ProductID"), ForSale);
            ForSale = (ForSaleBO)super.read(rs.getString("ProductID"), conn);
            
            int temp;
            temp = rs.getInt("NEWUSED");
            if(temp == 0){
                ForSale.setNewUsed(false);
            }
            else{
                ForSale.setNewUsed(true);
            }
                        
            temp = rs.getInt("SOLD");
            if(temp == 0){
                ForSale.setSold(false);
            }
            else{
                ForSale.setSold(true);
            }
//            ForSale.setProduct(prodDAO.read(rs.getString("productID")));
            ForSale.setAlreadyInDB(true);
            ForSale.setDirty(false);
            
// save to the list
            list.add(ForSale);
        }//while
        
        stmt.close();
        ConnectionPool.getInstance().release(conn);
        return list;
    }
    
    /**
     * 
     * @param xid 
     * @throws edu.byu.isys413.group1E.DataException 
     * @throws java.sql.SQLException 
     * @throws edu.byu.isys413.group1E.ConnectionPoolException 
     * @return 
     */
    public synchronized ProductBO readBySKU(String xid) throws DataException, SQLException, ConnectionPoolException{
        
        String id;
        String query = "SELECT * FROM PRODUCT WHERE SKU = '" + xid + "'";
        
        Connection conn = ConnectionPool.getInstance().get();
        Statement stmt = conn.createStatement();
        ResultSet rs = stmt.executeQuery(query);
        conn.commit();
        ConnectionPool.getInstance().release(conn);
        
        if(rs.next()) {
            id = rs.getString("ProductID");            
        }else{
            throw new DataException("Object was not found in the database.");
        }
        
        ForSaleBO forSale = (ForSaleBO)read(id);        
        
        return forSale;        
    }
    
    
    /**
     * 
     * @param bo 
     * @param conn 
     * @throws java.sql.SQLException 
     * @throws edu.byu.isys413.group1E.DataException 
     * @throws edu.byu.isys413.group1E.ConnectionPoolException 
     */
    protected void update(ProductBO bo, Connection conn) throws SQLException, DataException, ConnectionPoolException {
        //update the DB
        ForSaleBO BO = (ForSaleBO)bo;
        
        super.updatePhysical(BO.getProductID(), conn);
        
        PreparedStatement pstmt = conn.prepareStatement("UPDATE For_Sale SET new_used = ?, sold = ? WHERE ProductID = ?");
        
        int temp;
        if(BO.getNewUsed() == true){
            temp = 1;
        }else{
            temp = 0;
        }        
        pstmt.setInt(1, temp);
        
        if(BO.getSold() == true){
            temp = 1;
        }else{
            temp = 0;
        }        
        pstmt.setInt(2, temp);
        
        pstmt.setString(3, BO.getProductID());
        pstmt.executeUpdate();
        pstmt.close();
        BO.setAlreadyInDB(true);
    }// end update
    
    synchronized void insert(ProductBO bo, Connection conn) throws SQLException, DataException, ConnectionPoolException {
//update the DB
        ForSaleBO BO = (ForSaleBO)bo;
        
        super.insertPhysical(BO.getProductID(), conn);
        
        PreparedStatement pstmt = conn.prepareStatement("INSERT INTO For_Sale (PRODUCTID, NEW_USED, SOLD)" +
                "VALUES (?, ?, ?)");
        
        pstmt.setString(1, BO.getProductID());
        
        int temp;
        if(BO.getNewUsed() == true){
            temp = 1;
        }else{
            temp = 0;
        }
        pstmt.setInt(2, temp);
        
        if(BO.getSold() == true){
            temp = 1;
        }else{
            temp = 0;
        }        
        pstmt.setInt(3, temp);
        pstmt.executeUpdate();
        pstmt.close();
// tell the object that it's now in the db (so we call update next time not insert)
        BO.setAlreadyInDB(true);
    }//end insert
}
